
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Linq.Extensions;
using Abp.Organizations;
using JYJ.AiYard.Common;
using JYJ.AiYard.StationManagement.TbYardDevices;
using JYJ.AiYard.StationManagement.TbYardDevices.Dtos;
using JYJ.AiYard.StationManagement.TbYardDevices.DomainService;
using JYJ.AiYard.StationManagement.TbYardDevices.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYardDevices
{
    /// <summary>
    /// Tb_YardDevice应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class Tb_YardDeviceAppService : AiYardAppServiceBase, ITb_YardDeviceAppService
    {
        private readonly IRepository<Tb_YardDevice, long> _entityRepository;

        private readonly ITb_YardDeviceManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public Tb_YardDeviceAppService(
        IRepository<Tb_YardDevice, long> entityRepository,
        ITb_YardDeviceManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }


        /// <summary>
        /// 获取Tb_YardDevice的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(Tb_YardDevicePermissions.Query)] 
        public async Task<PagedResultDto<Tb_YardDeviceListDto>> GetPaged(GetTb_YardDevicesInput input)
		{
            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
            // TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrEmpty(filterText.FilterText))
            {
                query = query.Where(o => o.TDev_Name.Contains(filterText.FilterText) || o.TDev_IP.Contains(filterText.FilterText) );
            }

			var count = await query.CountAsync();

			var entityList = await query               
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync(); 
			var entityListDtos =entityList.MapTo<List<Tb_YardDeviceListDto>>();

			return new PagedResultDto<Tb_YardDeviceListDto>(count,entityListDtos);
		}


        /// <summary>
        ///获取不同的设置信息
        /// </summary>
        /// <param name="TDev_Type"></param>
        /// <returns></returns>
        public async Task<List<Tb_YardDeviceListDto>> GetAllTbYardDeviceListByDevType(string TDev_Type,long StationId)
        {
            var tbDevice = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId && o.TDev_Type.Equals(TDev_Type) && o.IsDeleted == false).ToListAsync();

            var allTbDevice = tbDevice.MapTo<List<Tb_YardDeviceListDto>>();   
            return allTbDevice;
        }


        /// <summary>
        /// 通过指定id获取Tb_YardDeviceListDto信息
        /// </summary>
        [AbpAuthorize(Tb_YardDevicePermissions.Query)] 
		public async Task<Tb_YardDeviceListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<Tb_YardDeviceListDto>();
		}

		/// <summary>
		/// 获取编辑 Tb_YardDevice
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(Tb_YardDevicePermissions.Create,Tb_YardDevicePermissions.Edit)]
		public async Task<GetTb_YardDeviceForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTb_YardDeviceForEditOutput();
            Tb_YardDeviceEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<Tb_YardDeviceEditDto>(); 
			}
			else
			{
				editDto = new Tb_YardDeviceEditDto();
			}

			output.Tb_YardDevice = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改Tb_YardDevice的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(Tb_YardDevicePermissions.Create,Tb_YardDevicePermissions.Edit)]
		public async Task<Dictionary<string,string>> CreateOrUpdate(CreateOrUpdateTb_YardDeviceInput input)
		{
            if (input.Tb_YardDevice.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }

            if (input.Tb_YardDevice.Id.HasValue)
			{
				return await Update(input.Tb_YardDevice);
			}
			else
			{
				return await Create(input.Tb_YardDevice);
			}
		}


		/// <summary>
		/// 新增Tb_YardDevice
		/// </summary>
		[AbpAuthorize(Tb_YardDevicePermissions.Create)]
		protected virtual async Task<Dictionary<string,string>> Create(Tb_YardDeviceEditDto input)
		{
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                bool IsAssess = true;  //检验是否通过
                //检验同一场所，IP，机号不能重复
                var tbquery = await _entityRepository.GetAll().Where(o =>
                    o.Station_ID == input.Station_ID && (o.TDev_IP == input.TDev_IP || o.TDev_No==input.TDev_No)).ToListAsync();
                if (tbquery.Count > 0)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "机号及IP不能重复");
                }
                else
                {
                    //TODO:新增前的逻辑判断，是否允许新增  ; 
                    var entity = input.MapTo<Tb_YardDevice>();

                    entity = await _entityRepository.InsertAsync(entity);
                    result.Add("retype", "1");
                    result.Add("revalue", "添加成功");
                }
            }
            catch (Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "添加设备失败");
            }
            return result;

        }

		/// <summary>
		/// 编辑Tb_YardDevice
		/// </summary>
		[AbpAuthorize(Tb_YardDevicePermissions.Edit)]
		protected virtual async Task<Dictionary<string,string>> Update(Tb_YardDeviceEditDto input)
		{
            //TODO:更新前的逻辑判断，是否允许更新
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                bool IsAssess = true;  //检验是否通过
                //检验同一场所，IP，机号不能重复
                var tbquery = await _entityRepository.GetAll().Where(o =>
                    o.Station_ID == input.Station_ID &&
                    (o.TDev_IP == input.TDev_IP || o.TDev_No == input.TDev_No) && o.Id != input.Id).ToListAsync();

                if (tbquery.Count > 0)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "修改时机号及IP不能重复");
                }
                else
                {
                    var entity = await _entityRepository.GetAsync(input.Id.Value);
                    input.MapTo(entity);

                    // ObjectMapper.Map(input, entity);
                    await _entityRepository.UpdateAsync(entity);
                    result.Add("retype", "1");
                    result.Add("revalue", "修改成功");
                }
            }
            catch (Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "修改设备失败");
            }
            return result;

		}



		/// <summary>
		/// 删除Tb_YardDevice信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(Tb_YardDevicePermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
        {
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id, 0, "Device"))
            {
                throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除Tb_YardDevice的方法
		/// </summary>
		[AbpAuthorize(Tb_YardDevicePermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "Device"))
                {
                    throw new Exception(Id + "存在外键约束，不允许删除");
                }
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出Tb_YardDevice为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


